<template>
  <div @click="openImg">
    <el-upload
      class="pic-uploader-component component-pic-upload"
      :disabled="disabled"
      :action="http.adornUrl('/admin/file/upload/img')"
      :headers="{Authorization: cookie.get('bbcAuthorization_vp'),locale:lang}"
      :show-file-list="false"
      :on-success="handleUploadSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img
        v-if="modelValue"
        :src="checkFileUrl(modelValue)"
        class="pic"
        alt
      >
      <el-icon
        class="pic-uploader-icon"
      >
        <Plus />
      </el-icon>
    </el-upload>
    <el-dialog
      v-model="visible"
      :append-to-body="visible"
    >
      <img-show :src="modelValue" />
    </el-dialog>
  </div>
</template>

<script setup>
import ImageCompressor from 'compressorjs'
import cookie from 'vue-cookies'

const props = defineProps({
  modelValue: {
    default: '',
    type: String
  },
  disabled: {
    default: false,
    type: Boolean
  }
})
const emit = defineEmits(['update:modelValue'])

const lang = ref(localStorage.getItem('bbcLang') || 'zh_CN')
const visible = ref(false)

// 图片上传
const handleUploadSuccess = (response, file) => {
  emit('update:modelValue', file.response)
}

// 限制图片上传大小
const beforeAvatarUpload = async (file) => {
  const isLt2M = file.size / 1024 / 1024 < 99999
  if (!isLt2M) {
    // 0.5m~5m，从0.8开始循环。5m~10m，从0.6开始循环。10m以上就直接0.4。
    // 最低使用0.4
    let quality
    if (file.size / 1024 / 1024 < 5) {
      quality = 0.8
    } else if (file.size / 1024 / 1024 < 10) {
      quality = 0.6
    } else {
      quality = 0.4
    }
    try {
      let resultBlob
      let index = true
      while (index) {
        resultBlob = await ImageCompressorFn(file, quality)
        if (resultBlob.size / 1024 < 512 || quality <= 0.4) {
          index = false
        } else {
          quality = (quality * 10 - 2) / 10
        }
      }
      return new File([resultBlob], file.name, {
        type: file.type
      })
    } catch (error) {
      return Promise().reject()
    }
    // ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return true
}

const ImageCompressorFn = (file, quality) => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line no-new
    new ImageCompressor(file, {
      quality, // 压缩大小
      convertSize: 512000,
      success (result) {
        resolve(result)
      },
      error (err) {
        reject(err)
      }
    })
  })
}

const openImg = () => {
  if (props.disabled) {
    visible.value = true
  }
}

</script>

<style lang="scss" scoped>
:deep(.component-pic-upload) {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    .pic-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .pic {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
  .el-upload:hover {
    border-color: #409eff;
  }
}
</style>
